package cn.acrdpm.tools;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 *  获取本机ip
 * @author 张敏
 * @date 2021/3/1
 */
@Component
@Slf4j
public class IpTool {

    private String ip;

    @PostConstruct
    public void ip() {
        try {
            Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ipAddress = null;
            List<String> ips = new ArrayList<>();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                Enumeration addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ipAddress = (InetAddress) addresses.nextElement();
                    if (ipAddress != null && ipAddress instanceof Inet4Address) {
                        if (ipAddress.getHostAddress().equals("127.0.0.1")) {
                            continue;
                        } else {
                            ip = ipAddress.getHostAddress();
                            ips.add(ip);
                        }
                    }
                }
            }

            log.info("本机的IP包含 = {}", JsonUtils.toJson(ips));
            for (String ip : ips) {
                //ip最后一个.后的码
                String ipLast = ip.substring(ip.lastIndexOf(".") + 1);
                if (!"1".equals(ipLast)) {
                    this.ip = ip;
                    log.info("使用本机的IP = {}", ip);
                    break;
                }
            }
        } catch (Exception e) {
            log.error("IpTool初始化失败！", e);
            throw new RuntimeException("IpTool初始化失败！");
        }
    }

    public String getIp() {
        return ip;
    }

}
